import { defineStore } from 'pinia'
import router from '@/router'
import useMainStore from '../main/main'

import { login, getUserMenus, getUserById } from '@/service/login/login'
import localStorage from '@/utils/local-storage'

import { mapMenusToRoutes, menuToPermission } from '@/utils/map-menu'
import { ElNotification } from 'element-plus'

interface IState {
  token: string
  userInfo: any
  userMenu: any[]
  permissions: string[]
}

interface Iaccount {
  name: string
  password: string
}

const useLoginStore = defineStore('login', {
  state: (): IState => ({
    token: '',
    userInfo: {},
    userMenu: [],
    permissions: []
  }),
  actions: {
    async postLogin(account: Iaccount) {
      const name = account.name
      const password = account.password
      const res = await login({ name, password })
      console.log(res)

      if (res.data) {
        //开发环境下标记该项目,以便其他项目的本地缓存数据影响本系统
        localStorage.set('mark', 'hmyCMS')
        this.token = res.data.token
        localStorage.set('token', res.data.token)
        // 获取用户信息
        const userInfo = await getUserById(res.data.id)
        this.userInfo = userInfo.data
        localStorage.set('userInfo', userInfo.data)
        // 获取菜单数据
        const userMenu = await getUserMenus(userInfo.data.role.id)
        console.log(userMenu)
        this.userMenu = userMenu.data
        localStorage.set('userMenu', userMenu.data)

        this.initAction(async function () {
          await router.push('/main')
          ElNotification.success({
            type: 'success',
            message: '登陆成功 !'
          })
        })
      }
    },
    // 第一次登陆调用该方法初始化一些数据,并动态添加路由,之后刷新可以再main.ts直接调用该方法
    async initAction(cb?: () => void) {
      const mark = localStorage.get('mark')
      if (mark !== 'hmyCMS') {
        localStorage.clear()
      }
      const token = localStorage.get('token')
      const userInfo = localStorage.get('userInfo')
      const userMenu = localStorage.get('userMenu')

      if (token && userInfo && userMenu) {
        this.token = token
        this.userInfo = userInfo
        this.userMenu = userMenu
        // 初始化拿到部门数据和角色数据
        const mainStore = useMainStore()
        mainStore.initRDdataAction()
        //  获取当前用户的权限
        this.permissions = menuToPermission(this.userMenu)
        // 动态添加路由  //为什么这里要用本地缓存呢 为了实现刷新页面可以直接调这个方法拿到数据   注意事项：是否造成多次从缓存拿数据影响性能
        const getRoutes = mapMenusToRoutes(userMenu)
        for (const item of getRoutes) {
          router.addRoute('main', item)
        }
        // 跳转到首页,这样的话路由后置守卫就会执行两次
        // console.log(router.currentRoute.value.fullPath)
        // await router.push('/main')
        if (cb) cb()
      }
    }
  }
})

export default useLoginStore
